<template>
    <el-upload
        ref="uploadRef"
        :accept="types"
        v-model:file-list="fileList"
        :multiple="true"
        :auto-upload="false"
        :on-preview="handlePreview"
        :on-change="handleChange"
        :before-remove="beforeRemove"
    >
        <template #trigger>
            <el-button type="primary">选择文件</el-button>
        </template>
        <el-button style="margin-left: 1em" type="success" @click="uploadSubmit">点我上传</el-button>
        <template #tip>
            <div class="el-upload__tip">
                格式为pdf或docx，不超过20M。
            </div>
        </template>
    </el-upload>
    <el-dialog v-model="showPreview" title="预览" width="100%">
        <vue-office-docx
            v-if="isWord"
            :src="previewURL"
            @error="errorHandler"
        />
        <vue-office-pdf
            v-if="!isWord"
            :src="previewURL"
            @error="errorHandler"
        />
    </el-dialog>
</template>


<script setup>
//上传文件
import {onMounted, ref} from "vue";
import {createProjectResourceFileApi, deleteProjectResourceFileApi, getProjectFileById} from "@/apis/project";
import {ElMessageBox} from "element-plus";
import VueOfficePdf from "@vue-office/pdf";
import VueOfficeDocx from "@vue-office/docx";
import {getProjectUploadPresigned, uploadByPresignedUrl} from "@/apis/file";

const props = defineProps(["id"])
const types = "application/pdf,application/docx,application/xml,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
const uploadRef = ref(null)
let fileList = ref([])
//获取项目文件
const getProjectResource = async () => {
    const res = await getProjectFileById(props.id)
    console.log(res.data)
    fileList.value = res.data.map(value => {
        return {
            url: `${value}`,
            name: decodeURI(value.slice(value.lastIndexOf("/") + 1)),
            path: value,
            timer: null
        }
    })
}

//预览框
let showPreview = ref(false)
let previewURL = ref("")
let isWord = ref("")
const handlePreview = file => {
    if (file.raw) {
        isWord.value = !file.raw.type.includes("pdf")
        previewURL.value = URL.createObjectURL(file.raw);
        showPreview.value = true
    } else {
        //提供下载链接
        let a = document.createElement('a');
        let event = new MouseEvent('click');
        a.download = file.name;
        a.href = file.url;
        a.dispatchEvent(event);
    }
}

const errorHandler = () => {
    ElMessage.error("文件加载失败,请稍后再试")
}
//存储要上传的文件数量
let count = ref(0)
const handleChange = async (file, fileList) => {
    count.value++
    //判断上传格式
    const typeArr = types.split(",")
    let flag = false
    for (const type of typeArr) {
        if (file.raw.type.includes(type)) {
            flag = true
            break
        }
    }
    if (!flag) {
        ElMessage.error("很抱歉您上传的文件格式不是pdf或docx")
        fileList.pop()
        count.value--
        return
    }
    if (file.raw.size / 1024 / 1024 > 20) {
        ElMessage.error("您上传的文件大小超过了20MB")
        fileList.pop()
        count.value--
    }
}
const uploadSubmit = async () => {
    for (let index = fileList.value.length - count.value; index < fileList.value.length;index++){
        // console.log(index,fileList.value[index])
        fileList.value[index].status = "uploading"
        const url =  await getProjectUploadPresigned(fileList.value[index].raw.name);
        fileList.value[index].timer = setInterval(()=>{
            fileList.value[index].percentage++
            if(fileList.value[index].percentage === 99) clearInterval(fileList.value[index].timer)
        },10)
        await uploadByPresignedUrl(url.data, fileList.value[index].raw)
        await createProjectResourceFileApi(props.id, url.data.slice(0, url.data.lastIndexOf('?')))
        clearInterval(fileList.value[index].timer)
        fileList.value[index].percentage = 100
        fileList.value[index].status = "success"
        count.value--;
    }
    await getProjectResource()
    ElMessage.success("上传文件成功")
}

//删除文件
const beforeRemove = file => {
    return ElMessageBox.confirm(
        '确定删除吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        console.log(file)
            await deleteProjectResourceFileApi(props.id, file.path)
            clearInterval(file.timer)
            ElMessage.success("删除成功")
        }
    )
}
onMounted(() => {
    getProjectResource()
})
</script>

<style scoped>
:deep(.el-upload-list__item-name):hover {
    cursor: pointer;
}
</style>